package com.bxx.controller;

import com.bxx.pojo.Role;
import com.bxx.service.RoleClientService;
import com.bxx.util.PageUtil;
import com.bxx.util.R;
import com.bxx.vo.TreeNodeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/consumer/role")
public class RoleController {

    @Autowired
    private RoleClientService roleClientService;

    /**
     * 获取全部角色
     * @param pageUtil
     * @return
     */
    @GetMapping("/listRoles")
    public PageUtil<Role> listRoles(PageUtil<Role> pageUtil){
        return roleClientService.listRoles(pageUtil);
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/insertRole")
    public R insertRole(Role role){
        return roleClientService.insertRole(role);
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @DeleteMapping("/deleteRole")
    public R deleteRole(String roleId){
        return roleClientService.deleteRole(roleId);
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @PutMapping("/updateRole")
    public R updateRole(Role role){
        return roleClientService.updateRole(role);
    }

    @GetMapping("/getRoleHaveModuleAndPermissionConvertTree")
    public List<TreeNodeVO> getRoleHaveModuleAndPermissionConvertTree(String roleId){
        return roleClientService.getRoleHaveModuleAndPermissionConvertTree(roleId);
    }

    @PostMapping("/giveRoleSetModuleAndPermission")
    public R giveRoleSetModuleAndPermission(String roleId, HttpServletRequest request){
        //获取模块和权限数组
        String[] moduleIds = request.getParameterValues("moduleIds[]");
        String[] permissionIds = request.getParameterValues("permissionIds[]");
        List<String> moduleArr = Arrays.asList(moduleIds);
        List<Integer> moduleIdList = moduleArr.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<String> permissionIdList = new ArrayList<String>();
        if(permissionIds != null){
            permissionIdList = Arrays.asList(permissionIds);
        }

//        System.out.println("roleId>"+roleId);
//        System.out.println("moduleIds>" + Arrays.toString(moduleIds));
//        System.out.println("permissionIds>" +Arrays.toString(permissionIds));
        return roleClientService.giveRoleSetModulesAndPermissions(roleId,moduleIdList,permissionIdList);
    }
}
